package com.season.summer.bspgenerator.controller;


import com.season.summer.bspgenerator.entity.PackageInfo;
import com.season.summer.bspgenerator.service.GeneratorService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 代码生成器
 */
@RestController
@RequestMapping("/generator")
public class GeneratorController {


    @Autowired
    private GeneratorService generatorService;

    /**
     * 列表
     */
    @GetMapping()
    public Object list(HttpServletRequest request) {
        String tableName = request.getParameter("tableName");
        return generatorService.list(tableName);
    }

    @GetMapping("/{tableName}")
    public Object getInfo(@PathVariable String tableName) {
        return generatorService.getPackageInfo(tableName);
    }

    @PostMapping()
    public Object getCode(@RequestBody PackageInfo packageInfo) {
        generatorService.generatorCode(packageInfo);
        return "success";
    }

    @PostMapping("/download")
    public void download(@RequestBody PackageInfo packageInfo, HttpServletResponse response) {
        byte[] data = generatorService.generatorCodeZip(packageInfo);

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + packageInfo.getClassName() +"-code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        try {
            IOUtils.write(data, response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
